﻿namespace Hotel.Web.Controllers
{
    using System.Web.Mvc;
    using Hotel.Web.Models;
    using Hotel.Web.Helpers;
    using ManagementModule = Hotel.Module.Management;
    using ManagementModels = Hotel.Module.Management.Models;
    using ResourcesModule = Hotel.Module.Resources;

    /// <summary>
    /// Controller for creation and dealing with Assignments; creates new Service
    /// </summary>
    public class AssignmentController : Controller
    {
        //
        // GET: /Assignment/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Assignment task)
        {
            if (ModelState.IsValid)
            {
                CreateOrder(task);
                return View("SuccessCreateAssignment", task);
            }
            // Model is not valid!!! return page with errors
            return View(task);
        }

        [HttpGet]
        public ActionResult NewService()
        {
            return View();
        }

        [HttpPost]
        public ActionResult NewService(Assignment task)
        {
            if (ModelState.IsValid)
            {
                int OrderId = m_ManagementController.GetOrderIDByRoomNumber(task.RoomNumber);
                m_ResourcesController.CreateService(task.CurrentService.Name, task.CurrentService.Price, OrderId);
                CreateOrder(task);
                return View("SuccessCreateAssignment", task);
            }
            // Model is not valid!!! return page with errors
            return View(task);
        }

        public int CreateOrder(Assignment _assignment)
        {
            lock (Lockers._mutex)
            {
                ManagementModels.Assignment assignOrder = new ManagementModels.Assignment();
                _assignment.AssignTo(assignOrder);
                _assignment.ID = m_ManagementController.CreateAssignment(assignOrder);
                return _assignment.ID;
            }
        }

        private readonly ManagementModule.ManagementController m_ManagementController = Helpers.ServiceLocator.Instance.GetService(typeof(ManagementModule.IManagement)) as ManagementModule.ManagementController;
        private readonly ResourcesModule.HotelResourcesController m_ResourcesController = Helpers.ServiceLocator.Instance.GetService(typeof(ResourcesModule.IResourseManagment)) as ResourcesModule.HotelResourcesController;
    }
}
